package cmd

import (
	"fmt"
	"net"
	"os"
	"strings"
	"time"

	"github.com/AlecAivazis/survey/v2"
	"github.com/spf13/cobra"

	"gitee.com/ldysdy999/file-transfer-station/cloud-station/pro/store"
	"gitee.com/ldysdy999/file-transfer-station/cloud-station/pro/store/aliyun"
)

var (
	fileName   string
	bucketName string
)

var uploadCmd = &cobra.Command{
	Use:   "upload",
	Short: "上传到文件中转站",
	Long:  "将指定文件上传到文件中转站",
	RunE: func(cmd *cobra.Command, args []string) error {
		if vers {
			fmt.Println("0.0.1")
			return nil
		}
		getSecretKeyInput()

		p, err := getProvide(ossProvider)
		if err != nil {
			return err
		}

		// 为了防止文件都堆在一个文件夹里面 无法查看
		// 我们采用日期进行编码
		day := time.Now().Format("20060102")

		// 为了防止不同用户同一时间上传相同的文件
		// 我们采用用户的主机名作为前置
		hn, err := os.Hostname()
		if err != nil {
			ip := getOutBindIp()
			if ip != "" {
				hn = "unknow"
			} else {
				hn = ip
			}
		}

		objectName := fmt.Sprintf("%s%s%s", day, hn, fileName)

		fileURL, err := p.Upload(bucketName, objectName, fileName)
		if err != nil {
			return err
		}
		fmt.Printf("file:%s upload success\n", fileName)
		fmt.Printf("文件下载地址：%s\n", fileURL)
		fmt.Println("注意下载链接有效期为3天")
		return nil
	},
}

//获取主机名
func getOutBindIp() string {
	conn, err := net.Dial("upd", "baidu.com:80")
	if err != nil {
		return ""
	}
	defer conn.Close()
	ipaddr := strings.Split(conn.LocalAddr().String(), ":")
	return ipaddr[0]
}

//判断是那个云厂商，就返回对应的接口
func getProvide(ossPrivode string) (store.OSSUpload, error) {
	switch ossPrivode {
	case "aliyun":
		return aliyun.NewAliYunOSSUploader(aliAccessKey, aliSecretKey, endPoint)
	case "othercloud":
		return nil, fmt.Errorf("not impl")
	default:
		return nil, fmt.Errorf("unknown oss privier options [aliyun/qcloud]")
	}
}

//对AK，SK进行输入密文保护
func getSecretKeyInput() {
	promptAK := &survey.Password{
		Message: "Please type your AccessKey",
	}

	promptSK := &survey.Password{
		Message: "Please type your SecretKey",
	}

	survey.AskOne(promptAK, &aliAccessKey)
	fmt.Println()
	survey.AskOne(promptSK, &aliSecretKey)
	fmt.Println()
}

func init() {
	uploadCmd.PersistentFlags().StringVarP(&fileName, "filename", "f", "", "上传文件名称")
	uploadCmd.PersistentFlags().StringVarP(&bucketName, "bucketname", "b", "filetransferstation", "指定bucket名称")
	rootCmd.AddCommand(uploadCmd)
}
